package app.project.directionlensproject;

import java.util.ArrayList;
import java.util.Locale;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.drawable.ColorDrawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import app.project.directionlensproject.adapter.UserPlaceAdapter;
import app.project.directionlensproject.compasspro.RotationVectorCompass;
import app.project.directionlensproject.fragment.FgListPlace;
import app.project.directionlensproject.fragment.FgSetting;
import app.project.directionlensproject.map.MapActivity;
import app.project.directionlensproject.map.PlaceAddActivity;
import app.project.directionlensproject.model.Place;
import app.project.directionlensproject.shownearplace.ShowMeHillsActivity;
import app.project.directionlensproject.util.BundleKeys;
import app.project.directionlensproject.util.CommonUtils;
import app.project.directionlensproject.util.Constants;
import app.project.directionlensproject.util.Utilities;

import com.google.android.gms.maps.model.LatLng;
import com.viewpagerindicator.TabPageIndicator;
import com.viewpagerindicator.TabPageIndicator.OnTabReselectedListener;

public class ListPlaceActivity extends GeneralActivity {
	ViewPager mPager;
	boolean isUserPlace = false;
	private TextView tvName;
	private Button btnAddPlace;
	private DrawerLayout mDrawerLayout;
	private View mDrawerLeft;
	private View vSearch;
	private EditText edtSearch;
	private ImageView imvIc;
	public FgListPlace FgFavorite;
	private ArrayList<FgListPlace> fgs;

	// Event when click maker in mapview
	public static boolean isFinish = false;
	
	/* put this into your activity class */
	private SensorManager mSensorManager;
	private float mAccel; // acceleration apart from gravity
	private float mAccelCurrent; // current acceleration including gravity
	private float mAccelLast; // last acceleration including gravity

	public static boolean isCompass=false;
//	public static final int TAB_SYSTEM=0;
//	public static final int TAB_GOOGLE=1;
//	private int mTabSelect=TAB_SYSTEM;
	public static ArrayList<Place> listCurrentPlace;
	int cateID = -1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		Log.d("a", "create ListPlaceActivity");
		super.onCreate(savedInstanceState);
		
		boolean isEn = CommonUtils.getBooleanSetting(this, Constants.IS_EN, false);
		if (!isEn) {
			Configuration c = new Configuration(getResources().getConfiguration());
			c.locale = new Locale("vi");
			getResources().updateConfiguration(c, getResources().getDisplayMetrics());
		} else {
			Configuration c = new Configuration(getResources().getConfiguration());
			c.locale = Locale.ENGLISH;
			getResources().updateConfiguration(c, getResources().getDisplayMetrics());
		}
		
		setContentView(R.layout.activity_list_place);
		mPager = (ViewPager) findViewById(R.id.view_pager);
		tvName = (TextView) findViewById(R.id.tv_name);
		btnAddPlace = (Button) findViewById(R.id.btn_add);
		btnAddPlace.setText(R.string.add_place);
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerLeft = findViewById(R.id.left_drawer);
		mDrawerLayout.setDrawerShadow(new ColorDrawable(0x00ffffff), GravityCompat.START);
		vSearch = findViewById(R.id.btn_search);
		edtSearch = (EditText) findViewById(R.id.edt_search);
		imvIc = (ImageView) findViewById(R.id.imv_ic);

		/* do this in onCreate */
		mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		mSensorManager.registerListener(mSensorListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
				SensorManager.SENSOR_DELAY_NORMAL);
		mAccel = 0.00f;
		mAccelCurrent = SensorManager.GRAVITY_EARTH;
		mAccelLast = SensorManager.GRAVITY_EARTH;

		Fragment fgSetting = new FgSetting();
		getSupportFragmentManager().beginTransaction().add(R.id.content_layout, fgSetting).commit();

		isUserPlace = getIntent().getBooleanExtra(BundleKeys.IS_USER_PLACE, false);
		LatLng myPlace = Utilities.getInstance().getMyPlace(this);
		double locationX = myPlace.latitude;
		double locationY = myPlace.longitude;

		if (isUserPlace) {
			initUsePlace(locationX, locationY);
			imvIc.setImageResource(R.drawable.ic_unapprove);
			cateID=getIntent().getIntExtra(BundleKeys.CATE_ID, Constants.ID_C_ALL);
		} else {
			cateID = getIntent().getIntExtra(BundleKeys.CATE_ID, Constants.ID_C_ALL);
			String name = Constants.getNameCate(this, cateID);
			tvName.setText(name);
			imvIc.setImageResource(Constants.getDrawableID(cateID));
			initOnlySytemPlace(cateID, locationX, locationY);
		}

		initEvent();
	}

	private void initEvent() {
		if (isUserPlace) {
			mPager.setOnPageChangeListener(new OnPageChangeListener() {
				public void onPageSelected(int position) {
					if (isUserPlace) {
						if (position == 0) {
							tvName.setText(R.string.unapprove_place);
							ListPlaceActivity.listCurrentPlace = fgs.get(0).arrPlaces;
							imvIc.setImageResource(R.drawable.ic_unapprove);
						} else if (position == 1) {
							tvName.setText(R.string.approve_place);														
							ListPlaceActivity.listCurrentPlace = fgs.get(1).arrPlaces;
							imvIc.setImageResource(R.drawable.ic_approve);
						} else if (position == 2) {
							tvName.setText(R.string.favorite_place);													
							ListPlaceActivity.listCurrentPlace = fgs.get(2).arrPlaces;
							imvIc.setImageResource(R.drawable.ic_placefavorite);
						} else if (position == 3) {
							tvName.setText(R.string.system_place);														
						}
					}
				}

				public void onPageScrolled(int arg0, float arg1, int arg2) {

				}

				public void onPageScrollStateChanged(int arg0) {

				}
			});
		}
		btnAddPlace.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				startActivity(new Intent(ListPlaceActivity.this, PlaceAddActivity.class));
			}
		});
		vSearch.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				final String searchStr = edtSearch.getText().toString().trim();
				initSearchPlace(searchStr);
			}
		});
		edtSearch.setOnEditorActionListener(new OnEditorActionListener() {
			public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
				if (arg1 == EditorInfo.IME_ACTION_SEARCH) {
					final String searchStr = edtSearch.getText().toString().trim();
					initSearchPlace(searchStr);
				}
				return false;
			}

		});
		imvIc.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				try {
					mDrawerLayout.openDrawer(mDrawerLeft);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		findViewById(R.id.content_layout).setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {

			}
		});
	}

	private void initSearchPlace(String searchStr) {
		CommonUtils.hideSoftKey(this, edtSearch);
		LatLng myPlace = Utilities.getInstance().getMyPlace(this);
		double locationX = myPlace.latitude;
		double locationY = myPlace.longitude;
		Intent i = new Intent(this, SearchActivity.class);
		i.putExtra(BundleKeys.LOCATION_X, locationX);
		i.putExtra(BundleKeys.LOCATION_Y, locationY);
		i.putExtra(BundleKeys.SEARCH_STR, searchStr);
		startActivity(i);
	}

	private void initOnlySytemPlace(int cateID, double locationX, double locationY) {
		btnAddPlace.setVisibility(View.GONE);
		FgListPlace fg = new FgListPlace();
		Bundle b = new Bundle();
		b.putDouble(BundleKeys.LOCATION_X, locationX);
		b.putDouble(BundleKeys.LOCATION_Y, locationY);
		b.putInt(BundleKeys.CATE_ID, cateID);
		fg.setArguments(b);

		FgListPlace fgGoogle = new FgListPlace();
		Bundle b1 = new Bundle();
		b1.putDouble(BundleKeys.LOCATION_X, locationX);
		b1.putDouble(BundleKeys.LOCATION_Y, locationY);
		b1.putInt(BundleKeys.CATE_ID, cateID);
		b1.putBoolean(BundleKeys.IS_GOOGLE, true);
		b1.putInt(BundleKeys.TYPE_PLACE, FgListPlace.TYPE_GOOGLE_SEARCH);
		fgGoogle.setArguments(b1);

		fgs = new ArrayList<FgListPlace>();
		fgs.add(fg);
		fgs.add(fgGoogle);
		UserPlaceAdapter adapter = new UserPlaceAdapter(getSupportFragmentManager(), fgs);
		mPager.setAdapter(adapter);

		TabPageIndicator indicator = (TabPageIndicator) findViewById(R.id.indicator);
		indicator.setVisibility(View.VISIBLE);
		indicator.setViewPager(mPager,CommonUtils.getIntSetting(MyApplication.getAppContext(), Constants.TAB_CURRENT,0));
		
		indicator.setOnPageChangeListener(new OnPageChangeListener() {
			
			public void onPageSelected(int arg0) {
				CommonUtils.saveIntSetting(MyApplication.getAppContext(), Constants.TAB_CURRENT,arg0);
				ListPlaceActivity.listCurrentPlace = fgs.get(arg0).arrPlaces;			
				Log.e("Tab",arg0+"");
				//mTabSelect=arg0;
			}
			
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				
			}
			
			public void onPageScrollStateChanged(int arg0) {
				//Log.e("Index",arg0+"");
			}
		});
		
		indicator.setOnTabReselectedListener(new OnTabReselectedListener() {
			
			public void onTabReselected(int position) {
				// TODO Auto-generated method stub
				ListPlaceActivity.listCurrentPlace = fgs.get(position).arrPlaces;
				CommonUtils.saveIntSetting(MyApplication.getAppContext(), Constants.TAB_CURRENT,position);
			}
		});
	}

	private void initUsePlace(double locationX, double locationY) {
		btnAddPlace.setVisibility(View.VISIBLE);
		tvName.setText(R.string.unapprove_place);	
		fgs = new ArrayList<FgListPlace>();

		FgListPlace fgUnapprovePlace = new FgListPlace();
		Bundle b1 = new Bundle();
		b1.putDouble(BundleKeys.LOCATION_X, locationX);
		b1.putDouble(BundleKeys.LOCATION_Y, locationY);
		b1.putBoolean(BundleKeys.IS_GOOGLE, false);
		b1.putInt(BundleKeys.TYPE_PLACE, FgListPlace.TYPE_UNAPPROVE);
		fgUnapprovePlace.setArguments(b1);

		FgListPlace fgApprovePlace = new FgListPlace();
		Bundle b = new Bundle();
		b.putDouble(BundleKeys.LOCATION_X, locationX);
		b.putDouble(BundleKeys.LOCATION_Y, locationY);
		b.putBoolean(BundleKeys.IS_GOOGLE, false);
		b.putInt(BundleKeys.TYPE_PLACE, FgListPlace.TYPE_APPROVE);
		fgApprovePlace.setArguments(b);

		FgFavorite = new FgListPlace();
		Bundle b3 = new Bundle();
		b3.putDouble(BundleKeys.LOCATION_X, locationX);
		b3.putDouble(BundleKeys.LOCATION_Y, locationY);
		b3.putBoolean(BundleKeys.IS_GOOGLE, false);
		b3.putInt(BundleKeys.TYPE_PLACE, FgListPlace.TYPE_FAVORITE);
		FgFavorite.setArguments(b3);

		fgs.add(fgUnapprovePlace);
		fgs.add(fgApprovePlace);
		fgs.add(FgFavorite);

		UserPlaceAdapter adapter = new UserPlaceAdapter(getSupportFragmentManager(), fgs);
		mPager.setAdapter(adapter);
	}

	/**
	 * event sensor of device change
	 */
	
	
	private final SensorEventListener mSensorListener = new SensorEventListener() {
		private float oldCornerUpdate = 0;
		private boolean isFinish = false;

		public void onSensorChanged(SensorEvent se) {
			// Thang dung theo chieu doc thi y lon nhat
			// Thang dung theo chieu ngang thi x lon nhat
			// Nam mat song song voi mat dat thi z lon nhat
			float x = se.values[0];
			float y = se.values[1];
			float z = se.values[2];
			mAccelLast = mAccelCurrent;
			mAccelCurrent = (float) Math.sqrt((double) (x * x + y * y + z * z));
			float delta = mAccelCurrent - mAccelLast;
			mAccel = mAccel * 0.9f + delta; // perform low-cut filter

			if (x > y && x > z) {
				// cho nay la quay theo truc x.. thay doi gia tri tren truc y,z
				if(!isCompass){
					isCompass=true;
					//startActivity(new Intent(ListPlaceActivity.this,ShowMeHillsActivity.class));
					Intent it=new Intent(ListPlaceActivity.this,RotationVectorCompass.class);
					it.putExtra(BundleKeys.IS_LIST, true);
					it.putExtra(BundleKeys.IS_USER_PLACE, isUserPlace);
					it.putExtra(BundleKeys.CATE_ID, cateID);
					//it.putExtra(BundleKeys.IS_TAB_SELECT,mTabSelect);
					startActivity(it);	
				}
				
			}
			if (y > x && y > z) {

				float corner = (float) (x * 180 / Math.PI);
				// Log.e("Change rotate",Math.abs(oldCornerUpdate - corner)+"");
				if (Math.abs(oldCornerUpdate - corner) > 20) {
					oldCornerUpdate = corner;
					for (FgListPlace fg : fgs) {
						fg.updateRotate(corner);
					}
				}
			}
			if (z > x && z > y) {
				//nam song song voi mat dat
				float corner = (float) (y * 180 / Math.PI);
				if (Math.abs(oldCornerUpdate - corner) > 5) {
					oldCornerUpdate = corner;
					for (FgListPlace fg : fgs) {
						fg.updateRotate(corner);
					}
				}
				//Log.e("Goc ",corner+"");
				//cho nay cung update lai listview compass
			}

		}

		public void onAccuracyChanged(Sensor sensor, int accuracy) {
		}
	};

	@Override
	public void onConfigurationChanged(android.content.res.Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
			if (!isFinish) {
				Intent i = new Intent(ListPlaceActivity.this, MapActivity.class);
				i.putExtra(BundleKeys.PREV_PAGE, Constants.FROM_LISTPLACE);
				i.putExtra(BundleKeys.CATE_ID, cateID);
				i.putExtra(BundleKeys.IS_USER_PLACE, isUserPlace);
				startActivity(i);
				ListPlaceActivity.this.finish();
				isFinish = true;
			}
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		mSensorManager.registerListener(mSensorListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
				SensorManager.SENSOR_DELAY_NORMAL);
	}

	@Override
	protected void onPause() {
		mSensorManager.unregisterListener(mSensorListener);
		super.onPause();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_MENU) {
			// open menu
			try {
				mDrawerLayout.openDrawer(mDrawerLeft);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if(keyCode == KeyEvent.KEYCODE_BACK){
			CommonUtils.saveIntSetting(MyApplication.getAppContext(), Constants.TAB_CURRENT,0);
			ListPlaceActivity.this.finish();
			startActivity(new Intent(ListPlaceActivity.this,HomeActivity.class));
			
			//go to category
		}
		return super.onKeyDown(keyCode, event);
	}

	public void updateData(boolean isShowProgress) {
		try {
			for (FgListPlace fg : fgs) {
				fg.updateData(isShowProgress);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

//	@Override
//	public void onBackPressed() {
//		super.onBackPressed();
//	}
	
	
}
